// src/composables/useLocalStorageTodos.ts
import { ref, watch } from 'vue'
import type { Todo } from '@/types'

export function useLocalStorageTodos() {
  const todoList = ref<Todo[]>([])
  
  // 获取当前用户的key
  const getCurrentUserKey = () => {
    const currentUser = localStorage.getItem('currentUser')
    if (currentUser) {
      const user = JSON.parse(currentUser)
      return `todos_${user.email}` // 使用邮箱作为用户标识
    }
    return 'todos_default' // 默认key
  }

  // 从localStorage加载数据
  const loadFromLocalStorage = () => {
    const userKey = getCurrentUserKey()
    const savedTodos = localStorage.getItem(userKey)
    if (savedTodos) {
      todoList.value = JSON.parse(savedTodos)
    } else {
      todoList.value = []
    }
  }

  // 保存到localStorage
  const saveToLocalStorage = (todos: Todo[]) => {
    const userKey = getCurrentUserKey()
    localStorage.setItem(userKey, JSON.stringify(todos))
  }

  // 初始化加载
  loadFromLocalStorage()

  return {
    todoList,
    saveToLocalStorage,
    loadFromLocalStorage
  }
}